package com.zzp.basepresenter.listener;

import android.annotation.SuppressLint;
import android.os.Build;
import android.os.Handler;
import android.os.Message;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;

import com.zzp.basepresenter.util.LoggerUtils;

import org.json.JSONException;

import java.io.IOException;
import java.util.HashMap;
import java.util.concurrent.ThreadLocalRandom;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public class OkHttpCallbackImpl implements Callback {
    private int success = 0x193;
    private int failed = 0x194;
    private int finished = 0x195;

    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == success) {
                try {
                    onJson(String.valueOf(msg.obj));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else if (msg.what == failed) {
                onError((Call) ((HashMap) msg.obj).get("Call"), (IOException) ((HashMap) msg.obj).get("IOException"));
            } else if (msg.what == finished) {
                onFinish(((boolean) msg.obj));
            }
        }
    };

    public OkHttpCallbackImpl() {

    }


    @Override
    public void onFailure(Call call, IOException e) {
        LoggerUtils.getInstance().i("failed to connect to socket\t\t" + e.toString());
        failed = random(0, 5555);
        HashMap<String, Object> map = new HashMap<>();
        map.put("Call", call);
        map.put("IOException", e);
        Message message = new Message();
        message.what = failed;
        message.obj = map;
        handler.sendMessage(message);
    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {
        String json = response.body().string();
        if (json == null || json.equals("")) {
            LoggerUtils.getInstance().i("return json is null");
            return;
        }
        success = random(5556, 9999);
        Message message = new Message();
        message.what = success;
        message.obj = json;
        handler.sendMessage(message);
        LoggerUtils.getInstance().i(response.code() + "\t\t" + response.request().toString() + "\nJson \t\t" + json);
    }

    @SuppressLint("NewApi")
    public void onJson(String s) throws JSONException {
        Message message = new Message();
        message.what = finished;
        message.obj = true;
        handler.sendMessageDelayed(message, 500);
    }

    public void onError(Call call, IOException e) {
        LoggerUtils.getInstance().i("Error All  = " + call.timeout().timeoutNanos() + "----- detail = " + e.getMessage());
        Message message = new Message();
        message.what = finished;
        message.obj = false;
        handler.sendMessageDelayed(message, 500);
    }

    public void onFinish(boolean success) {
        LoggerUtils.getInstance().i("finished all socket ---" + success);
    }

    private int random(int MIX_RANGE, int MAX_RANGE) {
        return ThreadLocalRandom.current().nextInt(MIX_RANGE, MAX_RANGE);
    }
}
